#!/bin/bash

# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

PM_PACKMAN_VERSION=6.1.3

# Specify where packman command exists
export PM_INSTALL_PATH="$(dirname "${BASH_SOURCE}")"

add_packages_root_to_file()
{
	FILE_PATH=$1
	if [ -f "$FILE_PATH" ]; then
		if ! grep -Fq "PM_PACKAGES_ROOT" $FILE_PATH ; then
			echo "Adjusting $FILE_PATH"
			echo -e "export PM_PACKAGES_ROOT=\$HOME/packman-repo\n" >> $FILE_PATH
		fi
	fi
}

# The packages root may already be configured by the user
if [ -z "$PM_PACKAGES_ROOT" ]; then
	# Set variable permanently using .profile for this user (if exists)
	add_packages_root_to_file ~/.profile
	add_packages_root_to_file ~/.bashrc
	# Set variable temporarily in this process so that the following execution will work
	export PM_PACKAGES_ROOT="${HOME}/packman-repo"
fi

# Ensure the packages root path exists:
if [ ! -d "$PM_PACKAGES_ROOT" ]; then
	echo "Creating packman packages repository at $PM_PACKAGES_ROOT"
	mkdir -p "$PM_PACKAGES_ROOT"
fi

# The packman module may be externally configured
if [ -z "$PM_MODULE_DIR_EXT" ]; then
	PM_MODULE_DIR="$PM_PACKAGES_ROOT/packman-common/$PM_PACKMAN_VERSION"
else
    PM_MODULE_DIR="$PM_MODULE_DIR_EXT"
fi
export PM_MODULE="$PM_MODULE_DIR/packman.py"

fetch_file_from_s3()
{
	SOURCE=$1
	SOURCE_URL=http://packman-bootstrap.s3.amazonaws.com/$SOURCE
	TARGET=$2
	echo "Fetching $SOURCE from S3 ..."
	if command -v wget >/dev/null 2>&1; then
		wget --quiet -O$TARGET $SOURCE_URL
	else
		curl -o $TARGET $SOURCE_URL -s -S
	fi
}

PLATFORM=`uname`
PROCESSOR=`uname -m`
PYTHON_VERSION=3.7.2

if [ $PLATFORM == 'Darwin' ]; then
	PYTHON_PACKAGE=$PYTHON_VERSION-macos-x86_64
elif [ $PLATFORM == 'Linux' ] && [ $PROCESSOR == 'x86_64' ]; then
	# This is temporary while we haven't built a static 3.7.2 that works on CentOS and Ubuntu
	PYTHON_PACKAGE=3.6.8-linux-x86_64
elif [ $PLATFORM == 'Linux' ] &&[ $PROCESSOR == 'aarch64' ]; then
	PYTHON_PACKAGE=$PYTHON_VERSION-linux-aarch64-static
else
	echo "Operating system not supported"
	exit 1
fi

PYTHON_INSTALL_FOLDER="$PM_PACKAGES_ROOT/python/$PYTHON_PACKAGE"
if [ ! -d "$PYTHON_INSTALL_FOLDER" ]; then
	mkdir -p "$PYTHON_INSTALL_FOLDER"
fi

export PM_PYTHON="$PYTHON_INSTALL_FOLDER/python"

if [ ! -f "$PM_PYTHON" ]; then
	fetch_file_from_s3 "python@$PYTHON_PACKAGE.tar.gz" "/tmp/python@$PYTHON_PACKAGE.tar.gz"
	if [ "$?" -eq "0" ]; then
		echo "Unpacking python"
		tar -xf "/tmp/python@$PYTHON_PACKAGE.tar.gz" -C "$PYTHON_INSTALL_FOLDER"
	else
		echo "Error downloading and extracting the python package"
		exit $?
	fi
fi

# Ensure the packman package exists:
if [ ! -f "$PM_MODULE" ]; then
	PM_MODULE_PACKAGE="packman-common@$PM_PACKMAN_VERSION.zip"
	TARGET="/tmp/$PM_MODULE_PACKAGE"
	# We always fetch packman from S3:
	fetch_file_from_s3 $PM_MODULE_PACKAGE $TARGET
	if [ "$?" -eq "0" ]; then
		echo "Unpacking ..."
		"$PM_PYTHON" -S -s -u -E "$PM_INSTALL_PATH/bootstrap/install_package.py" "$TARGET" "$PM_MODULE_DIR"
		rm $TARGET
	else
		echo "Failure while fetching packman module from S3!"
		exit 1
	fi
fi

# Ensure 7za package exists:
PM_7za_VERSION=16.02.4
export PM_7za_PATH="$PM_PACKAGES_ROOT/7za/$PM_7za_VERSION"
if [ ! -d "$PM_7za_PATH" ]; then
    export PM_7za_PATH="$PM_PACKAGES_ROOT/chk/7za/$PM_7za_VERSION"
    if [ ! -d "$PM_7za_PATH" ]; then
        "$PM_PYTHON" -S -s -u -E "$PM_MODULE" pull "$PM_MODULE_DIR/deps.packman.xml"
        if [ "$?" -ne 0 ]; then
           echo "Failure while installing required 7za package"
           exit 1
        fi
    fi
fi

# Generate temporary file name for environment variables:
PM_VAR_PATH=`mktemp -u -t tmp.$$.pmvars.XXXXXX`

if [ $# -ne 0 ]
  then
    PM_VAR_PATH_ARG=--var-path="$PM_VAR_PATH"
fi

"$PM_PYTHON" -S -s -u -E "$PM_MODULE" "$@" $PM_VAR_PATH_ARG
exit_code=$?
# Export the variables if the file was used and remove the file:
if [ -f "$PM_VAR_PATH" ]; then
	while read -r line
	do
        if [ ${#line} -gt 0 ]; then
    		export "$line"
        fi
	done < "$PM_VAR_PATH"
    rm -f "$PM_VAR_PATH"
fi

# Return the exit code from python
if [ "$exit_code" != 0 ]; then
    exit "$exit_code"
fi
